package org.dtrd.modules.system.util.qywx;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.common.exception.JeecgBootException;
import org.dtrd.common.util.DateUtils;
import org.dtrd.common.util.TimeUtil;
import org.dtrd.config.system.Constant;
import org.dtrd.config.wechat.config.WechatUtil;
import org.dtrd.modules.system.entity.bean.qiyeweixin.RobotMessage;
import org.dtrd.modules.system.entity.bean.qiyeweixin.RobotMessageRequest;
import org.dtrd.modules.util.FileUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 企业微信机器人工具类
 * @author qr
 * @date 2022/3/8 13:23
 */
@Component
@Slf4j
public class RobotUtil {

    public static RobotMessage signinRemain(String webhookurl, Constant.RecordType recordType, Integer subType, Integer patientId){
        RobotMessage.TemplateCard card = new RobotMessage.TemplateCard();
        RobotMessage.TemplateCard.TextContent mainTitle = new RobotMessage.TemplateCard.TextContent();
        mainTitle.setTitle("计划已执行提醒");
        mainTitle.setDesc("您当前时段的" + recordType.getName() + "请按计划更新记录");
        // 设置中间内容
        List<RobotMessage.TemplateCard.UrlContent> hcl = new ArrayList<>();
        RobotMessage.TemplateCard.UrlContent content1 = new RobotMessage.TemplateCard.UrlContent();
        content1.setKeyname("计划执行时间：");
        content1.setValue(DateUtil.format(new Date(), DatePattern.NORM_TIME_PATTERN));
        hcl.add(content1);
        RobotMessage.TemplateCard.UrlContent content2 = new RobotMessage.TemplateCard.UrlContent();
        content2.setKeyname("方案名称：");
        content2.setValue(recordType.getName() + "打卡");
        hcl.add(content2);
        RobotMessage.TemplateCard.UrlContent content3 = new RobotMessage.TemplateCard.UrlContent();
        content3.setKeyname("专家顾问：");
        content3.setValue("萧");
        hcl.add(content3);
        RobotMessage.TemplateCard.UrlContent content4 = new RobotMessage.TemplateCard.UrlContent();
        content4.setKeyname("备  注：");
        content4.setValue("如有疑问可以向您的医生和健管师进行咨询。^_^");
        hcl.add(content4);
        card.setHorizontal_content_list(hcl);
        // 设置跳转链接
        List<RobotMessage.TemplateCard.UrlContent> jumpList = new ArrayList<>();
        RobotMessage.TemplateCard.UrlContent jump1 = new RobotMessage.TemplateCard.UrlContent();
        jump1.setType(2);
        jump1.setTitle("小程序");
        jump1.setAppid(WechatUtil.getClientId());
        String pagePath = "/pages/checkin/checkin?recordType=" + recordType.getType() + "&subType=" + subType + "&recordtime=" + TimeUtil.getInstance().getStandardDate(DateUtils.datetimeFormat.get().toPattern());
        jump1.setPagepath(pagePath);
        jumpList.add(jump1);
        card.setJump_list(jumpList);
        // *跳转事件
        RobotMessage.TemplateCard.UrlContent cardAction = new RobotMessage.TemplateCard.UrlContent();
        cardAction.setType(1);
        cardAction.setUrl("http://h5.test.dtx-tech.com/patient/index.html?userid=" + patientId);
        card.setCard_action(cardAction);
        // 推送消息
        card.setMain_title(mainTitle);
        RobotMessage msg = RobotMessage.newsNotice(Constant.RobotMsgType.TEXT_NOTICE, card);
        HttpUtil.post(webhookurl, JSONUtil.toJsonStr(msg));
        return msg;
    }

    /**
     * 企微机器人推送消息
     * @param msgType 消息类型 {@link Constant.RobotMsgType}
     * @param request 封装推送内容
     * @param webhookurl 企微机器人的 webhookurl
     */
    public static RobotMessage sendMsg(Constant.RobotMsgType msgType, RobotMessageRequest request, String webhookurl) {
        RobotMessage msg = null;
        switch (msgType) {
            case TEXT:
                msg = new RobotMessage(msgType, request.getText());
                break;
            case MARKDOWN:
                msg = new RobotMessage(msgType, request.getMarkdown());
                break;
            case IMAGE:
                msg = new RobotMessage(msgType, handleUrl(request.getImageUrl()));
                break;
            case NEWS:
                msg = RobotMessage.news(msgType, request.getArticles());
                break;
            case FILE:
                msg = RobotMessage.file(msgType, request.getFile());
                break;
            case TEXT_NOTICE:
                msg = RobotMessage.textNotice(msgType, request.getText_notice());
                break;
            case NEWS_NOTICE:
                msg = RobotMessage.newsNotice(msgType, request.getNews_notice());
                break;
        }
        // 推送消息
        HttpUtil.post(webhookurl, JSONUtil.toJsonStr(msg));
        return msg;
    }

    public static String uploadFile(MultipartFile media, String key) {
        try {
            String url = String.format("https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=%s&type=file", key);
            HashMap<String, Object> params = new HashMap<>();
            File file = File.createTempFile("temp", "file");
            media.transferTo(file);
            params.put("media", file);
            String result = HttpUtil.post(url, params);
            // 解析上传结果
            JSONObject jsonObject = JSON.parseObject(result);
            return jsonObject.getString("media_id");
        }catch (Exception e) {
            throw new IllegalArgumentException("上传文件失败");
        }
    }

    private static RobotMessage.Image handleUrl(String imgUrl){
        URL url;
        InputStream is = null;
        OutputStream os = null;
        HttpURLConnection httpUrl = null;
        try{
            File tempFile = File.createTempFile("temp_file", FileUtil.getUrlFileName(imgUrl));
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            is = httpUrl.getInputStream();
            os = new FileOutputStream(tempFile);
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024 * 1024];
            int len;
            //使用一个输入流从buffer里把数据读取出来
            while( (len=is.read(buffer)) != -1 ){
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                os.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            String base64 = Base64.encode(tempFile);
            String md5 = SecureUtil.md5(tempFile);
            return new RobotMessage.Image(base64, md5);
        } catch (Exception e) {
            throw new JeecgBootException("获取文件失败");
        } finally{
            IoUtil.close(is);
            IoUtil.close(os);
            if(httpUrl != null)
            {
                httpUrl.disconnect();
            }
        }
    }
}
